//
//  SNKVideoDetailController.m
//  SleepNews
//
//  Created by Kavee DJ on 2017/1/1.
//  Copyright © 2017年 Kavee DJ. All rights reserved.
//

#import "SNKVideoDetailController.h"
#import "WMPlayer.h"
#import <UIImageView+WebCache.h>

@interface SNKVideoDetailController ()<WMPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *commentBtn;
@property (weak, nonatomic) IBOutlet UIView *detailVideoView;
@property (weak, nonatomic) IBOutlet UIImageView *videoBackgroundIV;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;

@property (strong, nonatomic) WMPlayer *wmPlayer;

@end

@implementation SNKVideoDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpCommentBtn];
}

-(void)dealloc{
    
    [self releaseWMPlayer];
}

- (void)setUpCommentBtn{
    self.commentBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.commentBtn.layer.borderWidth = 1.0f;
    self.commentBtn.layer.cornerRadius = 14.0f;
    self.commentBtn.layer.masksToBounds = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    
    [self.videoBackgroundIV sd_setImageWithURL:[NSURL URLWithString:self.videoCover] placeholderImage:[UIImage imageNamed:@"placeholder"]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self releaseWMPlayer];
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarHidden = NO;
}

- (IBAction)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)play:(UIButton *)sender {
    self.wmPlayer = [[WMPlayer alloc] initWithFrame:self.videoBackgroundIV.bounds];
    self.wmPlayer.delegate = self;
    self.wmPlayer.closeBtnStyle = CloseBtnStyleClose;
    self.wmPlayer.URLString = self.videoUrl;
    [self.detailVideoView addSubview:self.wmPlayer];
    
    [self.detailVideoView bringSubviewToFront:self.wmPlayer];
    [self.playBtn.superview sendSubviewToBack:self.playBtn];
    [self.wmPlayer play];
}

#pragma mark - 播放器代理方法
- (void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn {
    [self releaseWMPlayer];
    [self.playBtn.superview bringSubviewToFront:self.playBtn];
}

-(void)releaseWMPlayer{
    [self.wmPlayer pause];
    
    
    [self.wmPlayer removeFromSuperview];
    [self.wmPlayer.playerLayer removeFromSuperlayer];
    [self.wmPlayer.player replaceCurrentItemWithPlayerItem:nil];
    self.wmPlayer.player = nil;
    self.wmPlayer.currentItem = nil;
    //释放定时器，否侧不会调用WMPlayer中的dealloc方法
    [self.wmPlayer.autoDismissTimer invalidate];
    self.wmPlayer.autoDismissTimer = nil;
    
    
    self.wmPlayer.playOrPauseBtn = nil;
    self.wmPlayer.playerLayer = nil;
    self.wmPlayer = nil;
}

@end
